package com.hcb.micro.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.hcb.micro.dao.interfaceClass.AccountOpenidMapper;
import com.hcb.micro.dao.interfaceClass.AccountPlatformMapper;
import com.hcb.micro.dao.interfaceClass.OrderMapper;
import com.hcb.micro.dao.interfaceClass.UplevelLogMapper;
import com.hcb.micro.dto.AccountOpenid;
import com.hcb.micro.dto.AccountPlatform;
import com.hcb.micro.dto.Order;
import com.hcb.micro.dto.UplevelLog;
import com.hcb.micro.sdk.weixin.util.MD5Util;
import com.hcb.micro.service.IOrderService;
import com.hcb.micro.util.CommonHttpClient;
import com.hcb.micro.util.RequestHandler;

@Service("OrderService")
public class OrderServiceImpl implements IOrderService {

	@Autowired
	OrderMapper orderMapper;
	
	@Autowired
	AccountPlatformMapper accountPlatformDao;
	
	@Autowired
    private UplevelLogMapper uplevelLogDao;
	
	@Autowired
	private AccountOpenidMapper accountOpenidMapper;
	
	@Override
	public int deleteByPrimaryKey(Integer id) {
		return orderMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(Order record) {
		return orderMapper.insert(record);
	}

	@Override
	public int insertSelective(Order record) {
		return orderMapper.insertSelective(record);
	}

	@Override
	public Order selectByPrimaryKey(Integer id) {
		return orderMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(Order record) {
		return orderMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKey(Order record) {
		return orderMapper.updateByPrimaryKey(record);
	}

	@Override
	public List<Order> selectByAccountId(Map<String, Object> para) {
		return orderMapper.selectByAccountId(para);
	}

	@Override
	public List<Order> selectByMallUuid(Map<String, Object> para) {
		return orderMapper.selectByMallUuid(para);
	}

	@Override
	public List<Order> selectByAccountIdAndMallUuid(Map<String, Object> para) {
		return orderMapper.selectByAccountIdAndMallUuid(para);
	}

	@Override
	public List<Order> selectByPara(Map<String, Object> para) {
		return orderMapper.selectByPara(para);
	}

	@Override
	public Order selectByNumber(Integer number) {
		return orderMapper.selectByNumber(number);
	}

	/**
     * @param accountId
     * @param id
     * @param type 1打款 2拒绝
     * @throws Exception 
     * @see com.ygg.admin.service.qqbscash.QqbsCashService#updateLog(int, int, int)
     */
	public Map<String,Object> updateLog(int uplevelId ,HttpServletRequest request) throws Exception{
		Map<String,Object> result = new HashMap<>();
		UplevelLog ull = uplevelLogDao.selectByPrimaryKey(uplevelId);
		String openId = "";
		int accountId = 0;
		float payprice = 0f;
		if(ull != null){
			payprice = ull.getPayPrice()+1;
			accountId = ull.getAccountId();
        }else{
        	result.put("result", "1");
        	result.put("description", "申请记录不存在");
        	return result;
        }
		
		AccountOpenid ao = accountOpenidMapper.selectByAccountId(accountId);
		if(ao != null){
			openId = ao.getOpenId();
		}
        //打款
        /*RequestHandler reqHandler = new RequestHandler(null, null);
        String nonce_str = MD5Util.getNonceStr();
        
        reqHandler.setParameter("mch_appid","wx9ee7b554ae8f290b"); // 公众账号ID
        reqHandler.setParameter("mchid","1235604902"); // 商户号
        //随机字符串
        reqHandler.setParameter("nonce_str", nonce_str); 
        // 商家订单号
        reqHandler.setParameter("partner_trade_no", MD5Util.getNonceStr());
        //用户openid
        reqHandler.setParameter("openid", openId);
        //校验用户姓名选项
        reqHandler.setParameter("check_name", "NO_CHECK");
        //金额
        reqHandler.setParameter("amount", (int)(payprice * 100) + "");
        //企业付款描述信息
        reqHandler.setParameter("desc", "商盟惠购商城申请合伙人审核通过");
        //Ip地址
        reqHandler.setParameter("spbill_create_ip", request.getRemoteAddr());
        
         //key
        reqHandler.setKey("curtains170626curtains170626curt");
        
        // 生成签名
        String sign = reqHandler.createSign(reqHandler.getParameters());
        reqHandler.setParameter("sign", sign);
        String requestUrl = reqHandler.getRequestURL();
        //微信服务路径
        String cashUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        //商户号码
        String mchid = "1235604902";
        //下载的商户平台证书路径
        String certPath = "/lawyer/curtains/apiclient_cert.p12";
        JSONObject responseParams = CommonHttpClient.sendXmlRefundHTTP(cashUrl, mchid, certPath, requestUrl);	 
        if ("SUCCESS".equals(responseParams.getString("return_code")) && "SUCCESS".equals(responseParams.getString("result_code")))
        {
        	AccountPlatform ap = accountPlatformDao.selectByAccountId(accountId);
        	if(ap != null){
        		ap.setBepartner((byte)3);//成为合伙人，支付补偿费状态（0.未激活；1.已激活，未支付；2.已支付；3.升级成功）
        		ap.setIsPartner((byte)1);
        		
        		if(accountPlatformDao.updateByPrimaryKeySelective(ap) == 1){
        			//粉丝的shopAccountId以及FatherAccountId更新
            		Map<String,Object> paraAp = new HashMap<>();
            		paraAp.put("fatherAccountId", ap.getAccountId());
            		List<AccountPlatform> fansApList = accountPlatformDao.selectByPara(paraAp);
            		if(fansApList.size()>0){
            			for(AccountPlatform fansAp:fansApList){
            				fansAp.setPartnerAccountId(ap.getAccountId());
            				Integer updateFansAp = accountPlatformDao.updateByPrimaryKeySelective(fansAp);
                    		if(updateFansAp == 0){
                    			System.out.println("粉丝的partnerAccountId更新失败,accountId：" + accountId+",fansAccountId:"+fansAp.getAccountId());
                    			result.put("result", "1");
                            	result.put("description", "粉丝的partnerAccountId更新失败");
                            	return result;
                    		}else{
                        		System.out.println("粉丝的partnerAccountId更新成功,accountId：" + accountId+",fansAccountId:"+fansAp.getAccountId());
                        	}
            			}
            		}
        		}
        	}else{
        		result.put("result", "0");
            	result.put("description", "AccountPlatform记录不存在");
            	return result;
        	}
        }else{
        	result.put("result", "1");
        	result.put("description", "打款失败");
        	return result;
        }*/
		
		AccountPlatform ap = accountPlatformDao.selectByAccountId(accountId);
    	if(ap != null){
    		ap.setBepartner((byte)3);//成为合伙人，支付补偿费状态（0.未激活；1.已激活，未支付；2.已支付；3.升级成功）
    		ap.setIsPartner((byte)1);
    		
    		if(accountPlatformDao.updateByPrimaryKeySelective(ap) == 1){
    			//粉丝的shopAccountId以及FatherAccountId更新
        		Map<String,Object> paraAp = new HashMap<>();
        		paraAp.put("fatherAccountId", ap.getAccountId());
        		List<AccountPlatform> fansApList = accountPlatformDao.selectByPara(paraAp);
        		if(fansApList.size()>0){
        			for(AccountPlatform fansAp:fansApList){
        				fansAp.setPartnerAccountId(ap.getAccountId());
        				Integer updateFansAp = accountPlatformDao.updateByPrimaryKeySelective(fansAp);
                		if(updateFansAp == 0){
                			System.out.println("粉丝的partnerAccountId更新失败,accountId：" + accountId+",fansAccountId:"+fansAp.getAccountId());
                			result.put("result", "1");
                        	result.put("description", "粉丝的partnerAccountId更新失败");
                        	return result;
                		}else{
                    		System.out.println("粉丝的partnerAccountId更新成功,accountId：" + accountId+",fansAccountId:"+fansAp.getAccountId());
                    	}
        			}
        		}
    		}
    	}else{
    		result.put("result", "0");
        	result.put("description", "AccountPlatform记录不存在");
        	return result;
    	}
		
        result.put("result", "0");
    	result.put("description", "成功");
    	return result;
    }

	@Override
	public int updateOperationStatus(Order record) {
		return orderMapper.updateOperationStatus(record);
	}
}
